/*
 * @Author: MrRice
 * @Date: 2024-07-18 22:38:16
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-07-19 00:07:52
 * @FilePath: /workerCreator/src/workerCreator.ts
 * @Description:
 * -----小舟从此逝，江海寄余生----
 * Copyright (c) 2024 by 米大饭, All Rights Reserved.
 */
import { v4 as uuidv4 } from 'uuid';
export default class WorkerCreator {
  private _workerMap: Map<string, any> = new Map();
  constructor() {}

  /**  创建一个worker进程
   * @public
   * @param {string} codeString worker的js代码字符串
   * @returns {*}
   */
  public createWorker(codeString: string) {
    const blob = new Blob([codeString], { type: 'application/javascript' });
    const workerUrl = URL.createObjectURL(blob);
    const worker = new Worker(workerUrl);
    (worker as any).processID = uuidv4();
    URL.revokeObjectURL(workerUrl);
    return worker;
  }

  /**  添加一个worker的计算进程
   * @public
   * @param {string} code 需要计算运行的代码
   * @param {*} sendData 发送给计算进程的数据
   * @param {?(res: any) => void} [callback] 计算完成后的回调
   * @returns {void) => void}
   */
  public addWorker(code: string, sendData: any, callback?: (res: any) => void) {
    const worker = this.createWorker(code);
    this._workerMap.set((worker as any).processID, worker);

    worker.onmessage = (event: MessageEvent<any>) => {
      callback && callback(event.data);
      this._workerMap.delete((worker as any).processID);
      worker.terminate();
    };
    worker.postMessage(sendData);
  }
}
